import React, { useState, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { Flex, Toast } from 'antd-mobile'
import SearchBar from '../../components/SearchBar'
import { getCurrentCity } from '@/utils/city'
import Filter from '@/components/Filter'
import { getHouseList } from '@/api/houselist'
import {
  AutoSizer,
  List,
  WindowScroller,
  InfiniteLoader
} from 'react-virtualized'
import HouseItem from '@/components/HouseItem'
import Affix from '@/components/Affix'

function HouseList () {
  const [cityName, setCityName] = useState('深圳')
  const [count, setCount] = useState(0)
  const [houseList, setHouseList] = useState(null)
  const filterRef = useRef({})

  const getCityName = async () => {
    const { label: cityName } = await getCurrentCity()

    setCityName(cityName)
  }

  useEffect(() => {
    getCityName()
  }, [])

  const getHouseListData = async () => {
    Toast.loading('数据加载中...', 0)
    const { value } = await getCurrentCity()
    const res = await getHouseList({
      cityId: value,
      data: filterRef.current
    })
    Toast.hide()

    if (res.data.body.count > 0) {
      Toast.info(`共查询到 ${res.data.body.count} 套房源`, 1.5)
      setCount(res.data.body.count)
      setHouseList(res.data.body.list)
    }
  }

  const onConditionChange = data => {
    // 处理area 和 subway
    filterRef.current.area = null
    filterRef.current.subway = null
    if (data.area.length > 2) {
      filterRef.current[data.area[0]] =
        data.area[2] === 'null' ? data.area[1] : data.area[2]
    }

    // 出租方式
    if (data.mode.length > 0 && data.mode[0] !== 'null') {
      filterRef.current.rentType = data.mode[0]
    } else {
      filterRef.current.rentType = null
    }

    // 价格
    if (data.price.length > 0 && data.price[0] !== 'null') {
      filterRef.current.price = data.price[0]
    } else {
      filterRef.current.price = null
    }

    // 更多
    if (data.more.length > 0) {
      filterRef.current.price = data.mode.join(',')
    } else {
      filterRef.current.price = null
    }

    // 获取房源列表数据
    getHouseListData()
  }

  const rowRenderer = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // The List is currently being scrolled
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style // Style object to be applied to row (to position it)
  }) => {
    const item = houseList[index]
    if (!item) {
      return (
        <div style={style}>
          <div className={styles.loading}></div>
        </div>
      )
    }

    return (
      <div key={key} style={style}>
        <HouseItem key={item.houseCode} {...item} />
      </div>
    )
  }

  const isRowLoaded = ({ index }) => {
    return !!houseList[index]
  }

  const loadMoreRows = ({ startIndex, stopIndex }) => {
    return new Promise(async (resolve, reject) => {
      Toast.loading('数据加载中...', 0)
      const { value } = await getCurrentCity()
      const res = await getHouseList({
        cityId: value,
        data: filterRef.current,
        start: startIndex,
        end: stopIndex
      })
      Toast.hide()

      if (res.data.body.count > 0) {
        Toast.info(`共查询到 ${res.data.body.count} 套房源`, 1.5)
        setCount(res.data.body.count)
        setHouseList([...houseList, ...res.data.body.list])
      }
    })
  }

  return (
    <div className={styles.root}>
      <Flex className={styles.listHeader}>
        <i className='iconfont icon-back'></i>
        <SearchBar cityName={cityName} className={styles.mySearchBar} />
      </Flex>
      <Affix>
        <Filter onConditionChange={onConditionChange} />
      </Affix>
      <div className={styles.houseList}>
        {houseList && (
          <InfiniteLoader
            isRowLoaded={isRowLoaded}
            loadMoreRows={loadMoreRows}
            rowCount={count}
            minimumBatchSize={20}
          >
            {({ onRowsRendered, registerChild }) => (
              <WindowScroller>
                {({ height, scrollTop }) => (
                  <AutoSizer>
                    {({ height, width }) => (
                      <List
                        autoHeight
                        height={height}
                        rowCount={count}
                        rowHeight={120}
                        rowRenderer={rowRenderer}
                        scrollTop={scrollTop}
                        width={width}
                        onRowsRendered={onRowsRendered}
                      />
                    )}
                  </AutoSizer>
                )}
              </WindowScroller>
            )}
          </InfiniteLoader>
        )}
      </div>
    </div>
  )
}

export default HouseList
